<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-title">
        <h2>预集成测试管理平台</h2>
        <p>请登录您的账号</p>
      </div>
      
      <form class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="username"
            type="text"
            placeholder="请输入用户名"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="password"
            type="password"
            placeholder="请输入密码"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <button
            type="button"
            class="login-btn"
            @click="handleLogin"
            :disabled="loading"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </div>
        <div class="form-group" style="text-align: center;">
          <button
            type="button"
            class="register-link"
            @click="toggleRegisterForm"
          >
            {{ showRegisterForm ? '返回登录' : '注册账号' }}
          </button>
        </div>
      </form>
    </div>

    <!-- 注册表单 -->
    <div v-if="showRegisterForm" class="login-form-wrapper">
      <div class="login-title">
        <h2>注册账号</h2>
        <p>请填写以下信息完成注册</p>
      </div>
      
      <form class="login-form">
        <div class="form-group">
          <label for="reg-username">用户名</label>
          <input
            id="reg-username"
            v-model="registerUsername"
            type="text"
            placeholder="请输入用户名"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="reg-password">密码</label>
          <input
            id="reg-password"
            v-model="registerPassword"
            type="password"
            placeholder="请输入密码"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="reg-confirm-password">确认密码</label>
          <input
            id="reg-confirm-password"
            v-model="registerConfirmPassword"
            type="password"
            placeholder="请再次输入密码"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="reg-realname">真实姓名</label>
          <input
            id="reg-realname"
            v-model="registerRealName"
            type="text"
            placeholder="请输入真实姓名"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <button
            type="button"
            class="login-btn"
            @click="handleRegister"
            :disabled="loading"
          >
            {{ loading ? '注册中...' : '注册' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { login, register } from '@/api/user.js'
import router from '@/router'

// 简化表单数据定义
const username = ref('admin')
const password = ref('admin123')
const loading = ref(false)

// 注册表单数据
const showRegisterForm = ref(false)
const registerUsername = ref('')
const registerPassword = ref('')
const registerConfirmPassword = ref('')
const registerRealName = ref('')

const handleLogin = async () => {
  try {
    loading.value = true
    
    console.log('Login form data:', {
      username: username.value,
      password: password.value
    })
    console.log('API URL being called: /auth/login')
    
    // 先尝试登录
    let result = await login({
      username: username.value,
      password: password.value
    })
    console.log('Login result:', result)
    
    if (result && result.code === 200) {
      // 登录成功
      alert('登录成功')
      // 存储token和用户信息到localStorage
      if (result.data) {
        if (result.data.token) {
          localStorage.setItem('token', result.data.token)
        }
        // 存储用户信息 - 确保只存储userInfo对象，并且将role转换为roles数组格式
        const userInfoToStore = result.data.userInfo || result.data;
        // 统一角色格式为roles数组，以兼容前端各处使用
        if (userInfoToStore.role && !userInfoToStore.roles) {
          userInfoToStore.roles = [userInfoToStore.role];
        }
        // 确保用户信息包含头像字段
        if (!userInfoToStore.avatar && userInfoToStore.realName && userInfoToStore.realName.length > 0) {
          // 生成默认SVG头像
          userInfoToStore.avatar = `data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2240%22%20height%3D%2240%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2040%2040%22%20preserveAspectRatio%3D%22xMidYMid%20meet%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%23409EFF%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20font-family%3D%22Arial%22%20font-size%3D%2218%22%20font-weight%3D%22bold%22%20text-anchor%3D%22middle%22%20dy%3D%22.3em%22%20fill%3D%22white%22%3E${encodeURIComponent(userInfoToStore.realName.charAt(0))}%3C%2Ftext%3E%3C%2Fsvg%3E`;
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfoToStore))
      }
      // 跳转到首页
      router.push('/dashboard')
    } else {
      // 登录失败，尝试注册默认用户
      console.log('登录失败，尝试注册默认用户...')
      console.log('Error details:', result?.message || 'Unknown error')
      
      const defaultUser = {
        username: username.value,
        password: password.value,
        realName: '系统管理员',
        phone: '13800138000',
        email: 'admin@example.com',
        role: 'ADMIN',
        status: 1
      }
      
      console.log('Registering default user with data:', defaultUser)
      await register(defaultUser)
      console.log('Default user registered successfully')
      
      // 注册成功后再次尝试登录
      result = await login({
        username: username.value,
        password: password.value
      })
      console.log('Login result after registration:', result)
      
      if (result && result.code === 200) {
        alert('登录成功')
        // 存储token和用户信息
        if (result.data) {
          if (result.data.token) {
            localStorage.setItem('token', result.data.token)
          }
          // 存储用户信息 - 确保只存储userInfo对象，并且将role转换为roles数组格式
          const userInfoToStore = result.data.userInfo || result.data;
          // 统一角色格式为roles数组，以兼容前端各处使用
          if (userInfoToStore.role && !userInfoToStore.roles) {
            userInfoToStore.roles = [userInfoToStore.role];
          }
          // 确保用户信息包含头像字段
          if (!userInfoToStore.avatar && userInfoToStore.realName && userInfoToStore.realName.length > 0) {
            // 生成默认SVG头像
            userInfoToStore.avatar = `data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2240%22%20height%3D%2240%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2040%2040%22%20preserveAspectRatio%3D%22xMidYMid%20meet%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%23409EFF%22%2F%3E%3Ctext%20x%3D%2250%25%22%20y%3D%2250%25%22%20font-family%3D%22Arial%22%20font-size%3D%2218%22%20font-weight%3D%22bold%22%20text-anchor%3D%22middle%22%20dy%3D%22.3em%22%20fill%3D%22white%22%3E${encodeURIComponent(userInfoToStore.realName.charAt(0))}%3C%2Ftext%3E%3C%2Fsvg%3E`;
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfoToStore))
        }
        // 跳转到首页
        router.push('/dashboard')
      } else {
          alert(result?.message || '登录失败，请检查用户名或密码')
        }
      }
    } catch (error) {
      console.error('登录失败:', error)
      console.log('Error details:', error.response ? error.response.data : error.message)
      alert('登录失败，请检查网络或稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 切换注册表单显示
  const toggleRegisterForm = () => {
    showRegisterForm.value = !showRegisterForm.value
  }

  // 注册处理
  const handleRegister = async () => {
    try {
      // 简单验证
      if (!registerUsername.value || !registerPassword.value) {
        alert('请输入用户名和密码')
        return
      }
      
      if (registerPassword.value !== registerConfirmPassword.value) {
        alert('两次输入的密码不一致')
        return
      }
      
      loading.value = true
      
      const registerData = {
        username: registerUsername.value,
        password: registerPassword.value,
        realName: registerRealName.value || registerUsername.value,
        phone: '',
        email: '',
        role: 'USER', // 默认用户角色
        status: 1
      }
      
      console.log('Register data being sent:', registerData)
      console.log('API base URL:', import.meta.env.VITE_API_URL)
      console.log('Calling register API...')
      
      const result = await register(registerData)
      console.log('Register result:', result)
      
      if (result && result.code === 200) {
        alert('注册成功，请登录')
        // 清空注册表单并返回登录
        registerUsername.value = ''
        registerPassword.value = ''
        registerConfirmPassword.value = ''
        registerRealName.value = ''
        showRegisterForm.value = false
      } else {
        alert(result?.message || '注册失败，请稍后重试')
      }
    } catch (error) {
      console.error('Register error:', error)
      console.log('Error details:', error.response ? error.response.data : error.message)
      console.log('Error stack:', error.stack)
      alert('注册失败，请检查网络或稍后重试')
    } finally {
      loading.value = false
    }
  }
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form-wrapper {
  width: 400px;
  background-color: #fff;
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
}

.login-title h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
}

.login-title p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    color: #606266;
    font-weight: 500;
  }

  .form-input {
    width: 100%;
    height: 40px;
    padding: 0 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.3s;
  }

  .form-input:focus {
    outline: none;
    border-color: #409eff;
  }

  .login-btn {
    width: 100%;
    height: 40px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .login-btn:hover {
    background-color: #66b1ff;
  }

  .login-btn:disabled {
    background-color: #c0c4cc;
    cursor: not-allowed;
  }
  
  .register-link {
    background: none;
    border: none;
    color: #409eff;
    cursor: pointer;
    font-size: 14px;
    padding: 5px 10px;
    transition: color 0.3s;
  }
  
  .register-link:hover {
    color: #66b1ff;
  }
</style>